package com.zhuqi.handler;

import com.zhuqi.properties.NettyProperties;
import com.zhuqi.proto.HeartBeat;
import com.zhuqi.proto.build.HeatBeatProtoBuild;
import com.zhuqi.proto.cost.MessageProtocolBufEnum;
import com.zhuqi.session.messge.MessagePackage;
import com.zhuqi.util.ParamConst;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.SocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * <p>心跳处理器</p>
 * @author zhuqi
 * @since 2023/3/10 13:49
 */
@Slf4j
@ChannelHandler.Sharable
@Component
public class HeartBeatRequestMessageHandler extends SimpleChannelInboundHandler<HeartBeat.HeartBeatRequest> {

	@Resource
	private StringRedisTemplate stringRedisTemplate;

	@Resource
	private NettyProperties nettyProperties;

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, HeartBeat.HeartBeatRequest msg) {
		if (msg == null) {
			return;
		}
		Channel channel = ctx.channel();
		String name = msg.getName();
		String datetime = msg.getDatetime();
		log.info("HeartBeat入参name{}datetime{} == channel{}", name, datetime, channel);
		SocketAddress socketAddress = channel.localAddress();
		String address = socketAddress.toString();
		String key = ParamConst.SESSION_KEY + address;
		HeartBeat.HeartBeatResponse heartBeatResponse = HeatBeatProtoBuild.createHeartBeatResponse("续约成功");;
		MessagePackage messagePackage = new MessagePackage();
		messagePackage.setBusinessCode(MessageProtocolBufEnum.HEARTBEAT_RESPONSE_MESSAGE.getCode());
		// 更新redis
		stringRedisTemplate.opsForValue().set(key, address, nettyProperties.getExpireTime(), TimeUnit.SECONDS);
		messagePackage.setData(heartBeatResponse.toByteArray());
		ctx.channel().writeAndFlush(messagePackage);
	}
}
